<template>
	<view class="path-box" v-if="pathList.length">
		<image
			v-for="(item, index) in pathList"
			:src="item.svgUrl"
			:style="item.svgConfig"></image>
		<view v-for="(item, index) in pathList">
			<view
				class="zoneNumIconBox"
				v-show="item.svgConfig?.position?.y"
				:style="
					'top:' +
					item.svgConfig?.position?.y +
					'upx;left:' +
					item.svgConfig.position.x +
					'upx'
				">
				<view class="zoneNumIcon">
					<text>{{ index + 1 }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, reactive, computed } from "vue";
import YAML from "yaml";
import { useDeviceStore } from "@/stores/device";
import { useMapImage } from "@/utils/device";
const parseYaml = YAML.parse || YAML.safeLoad;
const { mapImageInfo } = useMapImage();
const deviceStore = useDeviceStore();
const props = defineProps<{
	mapImageInfo: MapImageInfo;
	TaskPathList?: PathItem;
	type?: string;
}>();
const pathList = ref<PathItem[]>([]);
const pathListRoute = ref<{ path: string[] }[]>([]);
const zonesList = ref<ZoneItem[]>([]);

const config = ref<PathConfig>({
	width: 0,
	height: 0,
	originX: 0,
	originY: 0,
	resolution: 1,
});
const ready = reactive({
	csv: false,
	yaml: false,
});
const isLoading = ref(false);
watch(
	() => [deviceStore.showGray],
	() => {},
	{ deep: true }
);
watch(
	() => deviceStore.zones,
	(val, oldVal) => {
		if (JSON.stringify(val) !== JSON.stringify(oldVal) && val.length) {
			pathListRoute.value = [];
			pathList.value = [];
			generatePaths();
		}
	},
	{ deep: true }
);

watch(
	() => props.mapImageInfo,
	(newVal, oldVal) => {
		if (!newVal.mapUrl || newVal.left == 0 || isLoading.value) return;
		isLoading.value = true;
		mapImageInfo.value = props.mapImageInfo;
		ready.csv = false;
		ready.yaml = false;
		pathListRoute.value = [];
		pathList.value = [];
		init();
	},
	{ deep: true }
);
// 初始化路径数组
const initPathArr = () => {
	pathList.value = zonesList.value.map(() => ({
		svgConfig: {
			width: "",
			height: "",
		},
	}));
	getMapYaml();
};

// 获取YAML配置
const getMapYaml = async () => {
	try {
		const mapStore = useUniversalStorage<string>("Map_Store", null);
		const defaultMap = deviceStore?.defaultDeviceMap || mapStore.value;
		const files = (await getYaml(
			defaultMap.map_info.map_docs[1].oss_url
		)) as YamlResult;
		config.value = {
			width: mapImageInfo.value.original.width,
			height: mapImageInfo.value.original.height,
			originX: -files.origin[0] / files.resolution,
			originY: -files.origin[1] / files.resolution,
			resolution: files.resolution,
		};
		const resolutionStore = useUniversalStorage("resolution", 1);
		resolutionStore.value = Number(files.resolution.toFixed(2));
		const orginStore = useUniversalStorage("origin", [0, 0]);
		orginStore.value = [
			Number(files.origin[0].toFixed(2)),
			Number(files.origin[1].toFixed(2)),
		];
		ready.yaml = true;
		checkReady();
	} catch (error) {
		console.error("加载YAML失败:", error);
	}
};

// 检查准备状态
const checkReady = () => {
	if (ready.csv && ready.yaml) {
		ready.csv = false;
		ready.yaml = false;
		generatePaths();
	}
};

// 获取CSV数据
const getCsvData = async () => {
	pathListRoute.value = [];

	for (const zone of zonesList.value) {
		try {
			const csvArr = await getCsv(zone.path);
			if (!csvArr) {
				ready.csv = false;
				return [];
			}
			pathListRoute.value.push({
				path: csvArr.split("\n"),
			});
		} catch (error) {
			console.error("加载CSV失败:", error);
		}
	}

	ready.csv = true;
	checkReady();
};

// 生成路径SVG
const generatePaths = () => {
	pathListRoute.value.forEach((path, j) => {
		if (!path.path) return;
		const resolution = config.value.resolution;
		const svgConfig = pathList.value[j].svgConfig;

		// 更新SVG配置
		svgConfig.width = `${
			(config.value.width / 4) * mapImageInfo.value.realScale
		}px`;
		svgConfig.height = `${
			(config.value.height / 4) * mapImageInfo.value.realScale
		}px`;
		// 构建SVG字符串
		let svg = `<svg viewBox="0 0 ${config.value.width / 4} ${
			config.value.height / 4
		}" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${
			config.value.width / 4
		}" height="${config.value.height / 4}"><g transform="translate(${
			config.value.originX / 4
		} ${config.value.originY / 4})">`;

		let dStart = "M";
		let dMaster = "M";
		let dEnd = "M";
		let dGray = "M";
		path.path.forEach((line, i) => {
			if (!line) return;
			const p = line.split(" ");
			const d = ` ${(Number(p[0]) / resolution / 4).toFixed(2)} ${(
				Number(p[1]) /
				resolution /
				4
			).toFixed(2)}`;
			// 进度逻辑处理
			const zone = deviceStore.zones[j] || [];
			const progress = zone?.progress || 0;
			if (progress > 0) {
				if (progress! < 0.1) {
					if (i < path.path.length * progress!) dGray += d;
					if (
						i >= path.path.length * progress! - 1 &&
						i < path.path.length * 0.1
					)
						dStart += d;
					if (
						i >= path.path.length * 0.1 - 1 &&
						i < path.path.length * 0.9
					)
						dMaster += d;

					if (i >= path.path.length * 0.9 - 1) dEnd += d;
				}
				if (progress! >= 0.1 && progress! < 0.9) {
					if (i < path.path.length * 0.1) dGray += d;

					if (
						i >= path.path.length * 0.1 - 1 &&
						i < path.path.length * progress!
					)
						dGray += d;
					if (
						i >= path.path.length * progress! - 1 &&
						i < path.path.length * 0.9
					)
						dMaster += d;
					if (i >= path.path.length * 0.9 - 1) dEnd += d;
				}

				if (progress! >= 0.9 && progress! < 1) {
					if (i < path.path.length * 0.1) dGray += d;

					if (
						i >= path.path.length * 0.1 - 1 &&
						i < path.path.length * 0.9
					)
						dGray += d;
					if (i >= 0.9 * progress! - 1) dGray += d;

					if (i >= path.path.length * progress! - 1) dEnd += d;
				}

				if (progress === 1) {
					if (i < path.path.length * 0.1) dGray += d;

					if (
						i >= path.path.length * 0.1 - 1 &&
						i < path.path.length * 0.9
					)
						dGray += d;
					if (i >= path.path.length * 0.9 - 1) dGray += d;
				}
			} else {
				// 默认路径生成逻辑
				if (i < path.path.length * 0.1) dStart += d;
				if (
					i >= path.path.length * 0.1 - 1 &&
					i < path.path.length * 0.9
				)
					dMaster += d;
				if (i >= path.path.length * 0.9 - 1) dEnd += d;
			}
			if (deviceStore.zones.length === 0 || !deviceStore.showGray) {
				if (i < path.path.length * 0.1) dStart += d;
				if (
					i >= path.path.length * 0.1 - 1 &&
					i < path.path.length * 0.9
				)
					dMaster += d;
				if (i >= path.path.length * 0.9 - 1) dEnd += d;
			}
		});
		if (deviceStore.zones.length === 0 || !deviceStore.showGray) {
			svg += `<path d="${dStart}" stroke="blue" stroke-width="1" stroke-opacity="0.7" fill="none"></path>`;
			svg += `<path d="${dMaster}" stroke="red" stroke-width="1" fill="none"></path>`;
			svg += `<path d="${dEnd}" stroke="green" stroke-width="1" stroke-opacity="0.4" fill="none"></path></g></svg>`;
		} else {
			if (deviceStore.zones[j]) {
				if (dGray !== "M") {
					svg += `<path d="${dStart}" stroke="blue" stroke-width="1" stroke-opacity="0.7" fill="none"></path>`;
					svg += `<path d="${dGray}" stroke="gray" stroke-width="1" stroke-opacity="1" fill="none"></path>`;
					svg += `<path d="${dMaster}" stroke="red" stroke-width="1" fill="none"></path>`;
					svg += `<path d="${dEnd}" stroke="green" stroke-width="1" stroke-opacity="0.4" fill="none"></path></g></svg>`;
				} else {
					svg += `<path d="${dStart}" stroke="blue" stroke-width="1" stroke-opacity="0.7" fill="none"></path>`;
					svg += `<path d="${dMaster}" stroke="red" stroke-width="1" fill="none"></path>`;
					svg += `<path d="${dEnd}" stroke="green" stroke-width="1" stroke-opacity="0.4" fill="none"></path></g></svg>`;
				}
			}
		}
		pathList.value[j].svgUrl = `data:image/svg+xml,${svg}`;
		pathList.value[j].svgConfig.transform = "scale(4)";
		pathList.value[j].svgConfig.top = `${
			(config.height / 2.66667) * mapImageInfo.value.realScale
		}px`;
		pathList.value[j].svgConfig.left = `${
			(config.width / 2.66667) * mapImageInfo.value.realScale
		}px`;
		let newArr: string[] = [];
		if (dStart) {
			newArr = dStart.split(" ");
		}
		if (dGray !== "M") {
			newArr = dGray.split(" ");
		}
		// 更新路径项
		pathList.value[j] = {
			svgConfig: {
				...svgConfig,
				transform: "scale(4)",
				top: `${
					(config.value.height / 2.66667) *
					mapImageInfo.value.realScale
				}px`,
				left: `${
					(config.value.width / 2.66667) *
					mapImageInfo.value.realScale
				}px`,
				"z-index": zonesList.value[j]?.zIndex || 1,
				position: {
					x: Math.abs(
						(-(
							config.value.originX / 4 +
							Number(dStart.split(" ")[1])
						) *
							4 *
							mapImageInfo.value.realScale +
							165 / 4 -
							15) *
							2
					),
					y: Math.abs(
						((config.value.height / 4 -
							config.value.originY / 4 -
							Number(dStart.split(" ")[2])) *
							mapImageInfo.value.realScale *
							4 -
							165 / 4 +
							10) *
							2
					),
				},
			},
			svgUrl: `data:image/svg+xml,${encodeURIComponent(svg)}`,
		};
	});
	// console.log(pathList.value);
};

// 获取YAML数据
const getYaml = (url: string): Promise<any> => {
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			success: (res) => {
				try {
					resolve(parseYaml(res.data));
				} catch (e) {
					reject(e);
				}
			},
			fail: reject,
		});
	});
};

// 获取CSV数据
const getCsv = (url: string): Promise<string> => {
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			success: (res) => resolve(res.data),
			fail: reject,
		});
	});
};
const init = async () => {
	initPathArr();
	await getCsvData();
};
const topHeight = ref("0");
onMounted(() => {
	// #ifdef APP-PLUS
	const statusBarHeight = ref(0);
	const systemInfo = uni.getSystemInfoSync();
	statusBarHeight.value = systemInfo.statusBarHeight || 0;
	topHeight.value = statusBarHeight.value + "px";
	// #endif
	zonesList.value =
		props.type == "addTask" ? deviceStore.selZone : deviceStore.zonesList;
});
watch(
	() => deviceStore.selZone,
	(val, oldVal) => {
		if (JSON.stringify(val) !== JSON.stringify(oldVal) && val.length) {
			pathList.value = [];
			zonesList.value = val;
			init();
		}
	},
	{ immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.path-box {
	position: absolute;
	top: 0;
	left: 0;
	pointer-events: none;
	will-change: transform;
	z-index: 2;
	:deep(img) {
		opacity: 1;
		transform: rotateX(180deg) translateZ(0);
	}
	:deep(div) {
		display: none;
	}
}
::v-deep uni-image {
	position: absolute;
}
.zoneNumIcon {
	width: 100rpx;
	height: 100rpx;
	background: url("/static/image/device/posNum.png") no-repeat;
	color: rgb(255, 255, 255);
	font-size: 28rpx;
	line-height: 85rpx;
	z-index: 99999;
	position: absolute;
	background-size: 100% 100%;

	text {
		display: inline-block;
		transform: rotateX(180deg) translateZ(0);
	}
}
.zoneNumIconBox {
	position: absolute;
	font-size: 120rpx;
	text-align: center;
	line-height: 100rpx;
	color: #666;
	z-index: 3;
	height: 165rpx;
	width: 165rpx;
	transform: rotateX(180deg) translateZ(0);
	opacity: 0.75;
}
</style>
